<template>
  <main class="home-view">
    <div class="search-box">
      <el-input maxLength="6" clearable v-model="stockCode" size="large" placeholder="输入股票代码" @input="handleChange" />
      <el-button :disabled="stockDataLoading" size="large" type="primary" @click="getStockList">查询</el-button>
      <el-button :disabled="stockDataLoading" size="large" type="primary" @click="exportStockList">导出</el-button>
    </div>
    <el-table row-key="代码" @sort-change="handleSortChange" v-loading="stockDataLoading" :data="currentStockList"
      @row-click="handleRowClick">
      <el-table-column label="股票名称">
        <template #default="scope">
          <el-text type="primary">{{ scope.row['名称'] }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="代码" label="股票代码" />
      <el-table-column prop="最新价" sortable="custom" label="当前价格">
        <template #default="scope">
          <el-text size="large" :type="scope.row['涨跌幅'] == 0 ? 'info' : scope.row['涨跌幅'] > 0 ? 'danger' : 'success'">{{
            scope.row['最新价'] }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="涨跌幅" sortable="custom" label="涨跌">
        <template #default="scope">
          <el-text size="large" :type="scope.row['涨跌幅'] == 0 ? 'info' : scope.row['涨跌幅'] > 0 ? 'danger' : 'success'">{{
            scope.row['涨跌幅'] }}%</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="最低" label="最低价" />
      <el-table-column prop="最高" label="最高价" />
      <el-table-column sortable="custom" prop="总市值" label="总市值"
        :formatter="(row) => formatToHundredMillion(row['总市值'])" />
      <el-table-column prop="成交额" label="成交金额" :formatter="(row) => formatToHundredMillion(row['成交额'])" />
    </el-table>
    <el-pagination v-model:current-page="currentPage" :page-sizes="[20, 50, 100, 200]" :default-page-size="pageSize"
      layout="total, sizes, prev, pager, next" :total="stockList.length" @current-change="handlePageChange"
      @size-change="handleSizeChange" />
  </main>
</template>
<script setup>
// 导入xlsx库
import * as XLSX from 'xlsx';
import { ref } from 'vue';
import { get } from '@/utils/request';
import { isBefore930OrAfter1501, formatToHundredMillion, debounce, getDateRange } from '@/utils/utils'
import { useStockDetailStore } from '@/stores/stock';
const stockCode = ref('');
const stockList = ref([]);
const currentStockList = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const stockDataLoading = ref(false);
const stockDetailStore = useStockDetailStore();

const getStockList = () => {
  const localStockList = localStorage.getItem('stockList');
  const isWeekend = new Date().getDay() === 0 || new Date().getDay() === 6;
  if (isBefore930OrAfter1501() || isWeekend) {
    if (localStorage.getItem('stockList')) {
      stockList.value = JSON.parse(localStockList)
      currentStockList.value = stockListChanage(JSON.parse(localStockList));
    } else {
      stockDataLoading.value = true;
      get('/stock_zh_a_spot_em').then(res => {
        const notDelisted = res.filter(item => item['最新价'] != null);
        stockList.value = notDelisted;
        currentStockList.value = stockListChanage(notDelisted);
        localStorage.setItem('stockList', JSON.stringify(notDelisted))
      }).finally(() => {
        stockDataLoading.value = false;
      });
    }
  } else {
    stockDataLoading.value = true;
    get('/stock_zh_a_spot_em').then(res => {
      const notDelisted = res.filter(item => item['最新价'] != null);
      stockList.value = notDelisted;
      currentStockList.value = stockListChanage(notDelisted);
    }).finally(() => {
      stockDataLoading.value = false;
    });
  }
};
// 创建一个防抖处理过的函数
const debouncedFilter = debounce((value) => {
  if (value.length > 3) {
    currentStockList.value = stockList.value.filter(item =>
      item['代码'].includes(value) || item['名称'].includes(value)
    )
  } else if (value.length == 0) {
    currentStockList.value = stockListChanage();
  }

}, 300);
const handleRowClick = (row) => {
  const { today, rangeDay } = getDateRange();
  stockDetailStore.setStockDetail(row);
  stockDetailStore.getKlineData(rangeDay, today, row);
}
const handleChange = (valval) => {
  debouncedFilter(valval);
};
const handleSortChange = (rowObj) => {
  if (rowObj.order == null) return;
  currentStockList.value = stockListChanage(stockList.value.sort((a, b) => {
    return rowObj.order === 'ascending' ? a[rowObj.prop] - b[rowObj.prop] : b[rowObj.prop] - a[rowObj.prop]
  }))

}
const stockListChanage = (inList = []) => {
  const handleList = inList.length ? inList : stockList.value;
  const returnList = handleList.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
  return returnList;
};
const handlePageChange = (val) => {
  currentPage.value = val;
  currentStockList.value = stockListChanage();
}
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentStockList.value = stockListChanage();
}
const exportStockList = ()=>{
  const exportList = currentStockList.value.map(item => ({
    股票代码: item['代码'],
    股票名称: item['名称'],
    当前价格: item['最新价'],
    涨跌: item['涨跌幅'],
    最低价: item['最低'],
    最高价: item['最高'],
    总市值: item['总市值'],
    成交金额: item['成交额'],
  }));

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(exportList);

  // 创建工作簿
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '股票数据');

  // 导出Excel文件
  XLSX.writeFile(wb, '股票数据.xlsx');
}
</script>
<style scoped>
.home-view {
  display: flex;
  flex-direction: column;
  width: 50vw;
  height: 100vh;
  padding: 20px;
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-box .el-input {
  padding-right: 10px;
}

.el-table {
  flex: 1;
}

.el-pagination {
  margin-top: 20px;
}
</style>